import {
  getRole
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      token
    } = userInfo
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', token)
      setToken(token)
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getRole().then(response => {
        if (!response.data) {
          reject('未授权或登录已过期，请重新登录')
        }
        const roleList = []
        if (response.data.role) {
          roleList.push(response.data.role.roleId)
        }
        const data = {
          roles: roleList,
          avatar: '',
          name: response.data.userName
        }
        const {
          roles,
          name,
          avatar
        } = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('权限未设定，请联系超级管理员设置')
        }
        const menuList = response.data.menuList
        if (!menuList || menuList.length <= 0) {
          reject('菜单未设定，请联系超级管理员设置')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_MENUS', menuList)
        resolve(data)
      }).catch(error => {
        reject(error)
        this.$router.push(`/login`)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, {
        root: true
      })
      resolve()
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {
      roles
    } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
